package com.tourlaid.mamagerment.service.impl

import com.tourlaid.mamagerment.entity.Shop
import com.tourlaid.mamagerment.enums.TldExceptionEnum
import com.tourlaid.mamagerment.mapper.ShopMapper
import com.tourlaid.mamagerment.service.ShopService
import com.tourlaid.mamagerment.util.LoginUtil
import com.tourlaid.mamagerment.util.TldException
import org.springframework.stereotype.Service
import org.springframework.util.StringUtils
import java.util.*
import javax.annotation.Resource

/**
 * Created by xiaoyongge on 2017/7/21.
 */
@Service("shopService")
class ShopServiceImpl : ShopService {
    override fun queryAllShop(): List<Shop> {
        return shopMapper!!.queryAllShop()
    }

    @Resource
    val shopMapper: ShopMapper? = null

    override fun queryForList(): List<Shop>? {
        return shopMapper!!.queryForList()
    }

    override fun insert(shopName: String?) {
        var shop = this.getByName(shopName)
        if (shop != null) {
            throw TldException(TldExceptionEnum.NAME_EXIST)
        }
        shop = Shop()
        shop.shopName = shopName
        shop.creator = LoginUtil.userId
        shop.editor = LoginUtil.userId
        shopMapper!!.insert(shop)
    }

    override fun getByName(shopName: String?): Shop? {
        if (StringUtils.isEmpty(shopName)) {
            throw TldException(TldExceptionEnum.NAME_NULL)
        }
        return shopMapper!!.getByName(shopName)
    }

    override fun getById(id: Long?): Shop? {
        id ?: return null
        var shop = shopMapper!!.getById(id)
        return shop
    }

    override fun update(id: Long?, shopName: String?) {
        id ?: throw TldException(TldExceptionEnum.ID_NULL)
        var oldShop = this.getByName(shopName)
        if (oldShop != null && !Objects.equals(id, oldShop.id)) {
            throw TldException(TldExceptionEnum.NAME_EXIST)
        }
        var newShop = Shop()
        newShop.id = id
        newShop.shopName = shopName
        newShop.editor = LoginUtil.userId
        shopMapper!!.update(newShop)
    }

    override fun queryByIdList(idList: List<Long?>): List<Shop> {
        return shopMapper!!.queryByIdList(idList)
    }

    override fun delete(id: Long?) {
        shopMapper!!.delete(id, LoginUtil.userId)
    }
}